<?php

namespace App\Jobs;

use App\Model\Good;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use MCS\MWSClient;
use Exception;

class SyncMwsJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $asinArr = [];

    /**
     * Create a new job instance.
     *
     * @param array $asinArr
     */
    public function __construct(array $asinArr)
    {
        //
        $this->asinArr = $asinArr;
        $this->queue = "sync_aws";
    }

    /**
     * Execute the job.
     *
     * @return void
     * @throws \Exception
     */
    public function handle()
    {

        if ($this->attempts() > 3) {
            return;
        }
        //
        try {
            $client = new MWSClient([
                'Marketplace_Id' => 'ATVPDKIKX0DER',
                'Seller_Id' => 'A1K5NAX8R0Z8GM',
                'Access_Key_ID' => 'AKIAIO5KTFSHNXUQEF7A',
                'Secret_Access_Key' => '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',
                'MWSAuthToken' => '' // Optional. Only use this key if you are a third party user/developer
            ]);

        } catch (Exception $e) {
            Log::info($e->getMessage());
            return;
        }

        // 每次最多5条
        try {
            $result = $client->GetMatchingProductForId(array_keys($this->asinArr));
        } catch (Exception $exception) {
            return;
        }

        $update = [];
        if (!empty($result['found'])) {
            foreach ($result['found'] as $asin => $info) {
                if (!empty($info[0]['medium_image'])) {
                    $update[] = [
                        'id' => $this->asinArr[$asin],
                        'amazon_img_url' => str_replace("_SL75_", "_SL500_", $info[0]['medium_image'])
                    ];
                }
            }
        }
        if ($update) {
            (new Good())->updateBatch($update);
        }

        sleep(1);
    }
}
